//
//  MTNewClubDetailMemberCell.swift
//  MT
//
//  Created by ooops on 2020/5/11.
//  Copyright © 2020 张强. All rights reserved.
//

import UIKit
import Foundation
import Eureka
import MTCategory

@objc public protocol MTNewClubDetailMemberCellDelegate: NSObjectProtocol {
    @objc optional func clickMoreButton(clickButton button: UIButton)
    @objc optional func clickAddCell()
    @objc optional func clickRemoveCell()
    @objc optional func didSelectCell(indexPath: IndexPath)
    @objc optional func didSelectCell(userName: String)
    @objc optional func didSelectCell(user: JMSGUser)
}

public class MTNewClubDetailMemberCell: Cell<String>, CellType {
    
    var group: JMSGGroup!
    weak var delegate: MTNewClubDetailMemberCellDelegate?
    
    private lazy var moreButton: UIButton = UIButton()
    fileprivate var count = 0
    fileprivate var sectionCount = 0
    fileprivate lazy var users: [JMSGUser?] = []
    fileprivate var isMyGroup = false
    fileprivate var currentUserCount = 0
    var marginLR: CGFloat = 16
    var spacing: CGFloat = 20
    var items: Int = 5
    var itemWidth: CGFloat {
        get {
            //return CGFloat((ScreenWidth - marginLR * 2 - CGFloat(items - 1) * spacing) / items)
            return (ScreenWidth - marginLR * 2 - CGFloat(items - 1) * CGFloat(spacing)) / CGFloat(items)
        }
    }
    
    var itemHeight: CGFloat {
        get {
            return itemWidth + 10
        }
    }
    
    private lazy var flowLayout: UICollectionViewFlowLayout = {
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.itemSize = CGSize(width: itemWidth, height: itemHeight)
        flowLayout.scrollDirection = .vertical
        flowLayout.minimumInteritemSpacing = 10
        flowLayout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 8, right: 0)
        flowLayout.minimumLineSpacing = 0
        return flowLayout
    }()
    
    private lazy var collectionView: UICollectionView = {
        let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: self.flowLayout)
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(MTNewClubDetailMemberAvatorCell.self, forCellWithReuseIdentifier: MTNewClubDetailMemberAvatorCell.reuseIdentity())
        collectionView.isScrollEnabled = false
        collectionView.backgroundColor = UIColor.clear
        return collectionView
    }()
    
    func bindData(_ group: JMSGGroup) {
        self.group = group
        _getData()
        self.collectionView.reloadData()
    }
    
    private func makeConstraint() {
        
    }
    
    override public func setup() {
        super.setup()
        self.backgroundColor = UIColor.theme.background
        self.selectionStyle = .none
        self.height = { UITableView.automaticDimension }
        _init()
        makeConstraint()
        NotificationCenter.default.addObserver(self, selector: #selector(_updateGroupInfo), name: NSNotification.Name(rawValue: kUpdateGroupInfo), object: nil)
        contentView.backgroundColor = UIColor(hex: 0xF4F4F4)
    }
    
    @objc private func _updateGroupInfo() {
        group.memberInfoList({ (result, error) in
            if let userInfos: [JMSGGroupMemberInfo] = result as? [JMSGGroupMemberInfo] {
                self.users = userInfos.map { (info) -> JMSGUser? in
                    return info.user
                }
            }
        })
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
            //.addObserver(self, selector: #selector(_updateGroupInfo), name: NSNotification.Name(rawValue: kUpdateGroupInfo), object: nil)
    }
    
    override public func update() {
        super.update()
        _getData()
        let showMore = isMyGroup ? count > 13 : count > 14
//        let showMore = isMyGroup ? count > 1 : count > 1
        moreButton.isHidden = !showMore
        let column = CGFloat(count / items)
        collectionView.snp.updateConstraints { (make) in
            make.height.equalTo((column == 0 ? 1 : column > 3 ? 3 : column) * itemHeight).priority(.high)
        }
        
//        if isMyGroup {
//            if count > 8 {
////                    addConstraint(_JCLayoutConstraintMake(collectionView, .height, .equal, nil, .notAnAttribute, 260))
//                collectionView.snp.updateConstraints { (make) in
//                    make.height.equalTo(300).priority(.high)
//                }
//            } else if count > 3 {
////                    addConstraint(_JCLayoutConstraintMake(collectionView, .height, .equal, nil, .notAnAttribute, 200))
//                collectionView.snp.updateConstraints { (make) in
//                    make.height.equalTo(240).priority(.high)
//                }
//            } else {
////                    addConstraint(_JCLayoutConstraintMake(collectionView, .height, .equal, nil, .notAnAttribute, 100))
//                collectionView.snp.updateConstraints { (make) in
//                    make.height.equalTo(200).priority(.high)
//                }
//            }
//        } else {
//            if count > 9 {
//                //addConstraint(_JCLayoutConstraintMake(collectionView, .height, .equal, nil, .notAnAttribute, 260))
//                collectionView.snp.updateConstraints { (make) in
//                    make.height.equalTo(300).priority(.high)
//                }
//            } else if count > 4 {
////                    addConstraint(_JCLayoutConstraintMake(collectionView, .height, .equal, nil, .notAnAttribute, 200))
//                collectionView.snp.updateConstraints { (make) in
//                    make.height.equalTo(240).priority(.high)
//                }
//            } else {
////                    addConstraint(_JCLayoutConstraintMake(collectionView, .height, .equal, nil, .notAnAttribute, 100))
//                collectionView.snp.updateConstraints { (make) in
//                    make.height.equalTo(200).priority(.high)
//                }
//            }
//        }
    }
    
    private func _init() {
        moreButton.isHidden = true
        addSubview(collectionView)
        
        moreButton.addTarget(self, action: #selector(_clickMore), for: .touchUpInside)
        moreButton.setTitleColor(UIColor.redpack.x5d5d5d, for: .normal)
        moreButton.titleLabel?.font = PingFangSCRegularFont(14)
        moreButton.setTitle("查看更多成员 >", for: .normal)
        self.addSubview(moreButton)
        
        moreButton.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.width.equalToSuperview()
            make.height.equalTo(26)
            make.bottom.equalToSuperview().offset(-14)
        }
        
        collectionView.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(16)
            make.right.equalToSuperview().offset(-16)
            make.top.equalToSuperview().offset(32)
            make.height.equalTo(200).priority(.high)
            make.bottom.equalTo(moreButton.snp.top).offset(-10)
        }
    }
    
    @objc func _clickMore() {
        delegate?.clickMoreButton?(clickButton: moreButton)
    }
    
    fileprivate func _getData() {
        self.users = group.memberArray()
        //self.users = self.users + self.users + self.users + self.users + self.users + self.users + self.users + self.users + self.users + self.users + self.users + self.users + self.users + self.users + self.users + self.users + self.users + self.users + self.users + self.users
        currentUserCount = users.count
        
        let user = JMSGUser.myInfo()
        if group.owner == user.username  {
            isMyGroup = true
        }
        
        count = users.count
        self.collectionView.reloadData()
    }
}

extension MTNewClubDetailMemberCell: UICollectionViewDataSource, UICollectionViewDelegate {
    
    public func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return users.count
    }

    public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        return collectionView.dequeueReusableCell(withReuseIdentifier: MTNewClubDetailMemberAvatorCell.reuseIdentity(), for: indexPath)
    }
    
    public func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        guard let cell = cell as? MTNewClubDetailMemberAvatorCell else {
            return
        }
        if let user = users[indexPath.item] {
            cell.bindDate(user: user)
        }
    }
    
    public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if let user = users[indexPath.item] {
            delegate?.didSelectCell?(userName: user.username)
            delegate?.didSelectCell?(user: user)
        }
    }
    
}


// The custom Row also has the cell: CustomCell and its correspond value
public final class MTNewClubDetailMemberRow: Row<MTNewClubDetailMemberCell>, RowType {
    required public init(tag: String?) {
        super.init(tag: tag)
        cellProvider = CellProvider<MTNewClubDetailMemberCell>.init()
    }
}
